package com.zmn.oms.business.impl.conf.distribute;

import com.google.common.collect.Lists;
import com.zmn.base.common.data.common.dro.area.AreaDRO;
import com.zmn.base.common.data.dubbo.interfaces.area.AreaListRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.cube.common.utils.CollectionUtil;
import com.zmn.oms.business.interfaces.conf.distribute.NonGridRobOrderConfigBService;
import com.zmn.oms.common.dro.conf.distribute.NonGridRobOrderConfigDRO;
import com.zmn.oms.model.dio.conf.distribute.NonGridRobOrderConfigDIO;
import com.zmn.oms.model.entity.conf.distribute.*;
import com.zmn.oms.model.vo.conf.distribute.DistributeWeightAreaVO;
import com.zmn.oms.model.vo.conf.distribute.NonGridRobOrderConfigVO;
import com.zmn.oms.services.interfaces.conf.distribute.NonGridRobOrderConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述
 *
 * @author fubiao
 * @since 2022/07/18
 */
@Service
public class NonGridRobOrderConfigBServiceImpl implements NonGridRobOrderConfigBService {

    @Autowired
    private NonGridRobOrderConfigService nonGridRobOrderConfigService;

    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false, timeout = 200000)
    private AreaListRemoteService areaListRemoteService;

    @Override
    public NonGridRobOrderConfigVO findByKey(Integer nonGridConfigId) {
        NonGridRobOrderConfig configInfo = nonGridRobOrderConfigService.findByKey(nonGridConfigId);
        return this.toVO(configInfo);
    }

    @Override
    public List<NonGridRobOrderConfigVO> listByPlatIdAndBizType(List<Integer> platIds, Integer bizType,
                                                                Integer distributeWay) {
        List<NonGridRobOrderConfig> configInfos = nonGridRobOrderConfigService.listByPlatIdAndBizType(platIds,
                bizType, distributeWay);
        final List<NonGridRobOrderConfigVO> configVOS = new ArrayList<>(configInfos.size());
        configInfos.stream().forEach(item -> {
            configVOS.add(this.toVO(item));
        });
        return configVOS;
    }

    @Override
    public List<NonGridRobOrderConfigDRO> listNoGridRobConfigByQuery(NonGridRobOrderConfigQuery configQuery) {
        List<NonGridRobOrderConfig> configInfos = nonGridRobOrderConfigService.listNoGridRobConfigByQuery(configQuery);
        if (CollectionUtil.isNotNullOrEmpty(configInfos)) {
            return this.toDRO(configInfos);
        }
        return new ArrayList<>(16);
    }

    @Override
    public List<DistributeWeightAreaVO> listCityByProvince(SearchCityQuery searchCityQuery) {
        if (Objects.isNull(searchCityQuery) || NumberUtil.isNullOrZero(searchCityQuery.getProvinceId())) {
            // 如果没有传省ID 返回空列表
            return new ArrayList<>();
        }
        CheckCityAvailableQuery query =
                CheckCityAvailableQuery.builder()
                        .nonGridConfigId(searchCityQuery.getNonGridConfigId())
                        .bizType(searchCityQuery.getBizType())
                        .plat(searchCityQuery.getPlat())
                        .provinceId(searchCityQuery.getProvinceId())
                        .build();
        List<Integer> beenSetCityIdList = nonGridRobOrderConfigService.hasBeenSetCity(query);
        ResponseDTO<List<AreaDRO>> listResponseDTO = areaListRemoteService.listAreaByParentId(searchCityQuery.getProvinceId());
        List<AreaDRO> baseAreaList = Optional.ofNullable(listResponseDTO.getData()).orElse(Lists.newArrayList());
        List<AreaDRO> result = baseAreaList.stream()
                .filter(item -> !beenSetCityIdList.contains(item.getAreaId()))
                .collect(Collectors.toList());
        return this.parseAreaToVO(result, searchCityQuery.getSelectedValue());
    }

    @Override
    public Integer countByQuery(NonGridRobOrderConfigQuery configQuery) {
        return nonGridRobOrderConfigService.countByQuery(configQuery);
    }

    @Override
    public Integer insert(NonGridRobOrderConfig nonGridRobOrderConfig) {
        return nonGridRobOrderConfigService.insert(nonGridRobOrderConfig);
    }

    @Override
    public Integer updateByKey(NonGridRobOrderConfigDIO dio) {
        NonGridRobOrderConfig updateNoGridRobOrderConfigQuery = new NonGridRobOrderConfig();
        BeanMapper.copy(dio, updateNoGridRobOrderConfigQuery);
        if (StringUtils.isNotEmpty(dio.getCancelTime())) {
            String cancelTime = dio.getCancelTime();
            String[] split = cancelTime.split(" ~ ");
            updateNoGridRobOrderConfigQuery.setCancelTimeStart(split[0]);
            updateNoGridRobOrderConfigQuery.setCancelTimeEnd(split[1]);
        }
        return nonGridRobOrderConfigService.update(updateNoGridRobOrderConfigQuery);
    }

    /**
     * 将区域对象转换称下拉框识别的VO对象
     *
     * @param baseAreaList
     * @return
     */
    private List<DistributeWeightAreaVO> parseAreaToVO(List<AreaDRO> baseAreaList, Integer selectedValue) {
        List<DistributeWeightAreaVO> distributeWeightAreaVOList = new ArrayList<>(baseAreaList.size());
        for (AreaDRO baseArea : baseAreaList) {
            DistributeWeightAreaVO distributeWeightAreaVO = DistributeWeightAreaVO.builder()
                    .value(baseArea.getAreaId())
                    .name(baseArea.getName())
                    .selected(Objects.equals(baseArea.getAreaId(), selectedValue))
                    .disabled(false)
                    .build();
            distributeWeightAreaVOList.add(distributeWeightAreaVO);
        }
        return distributeWeightAreaVOList;
    }

    /**
     *  db -> DRO
     * @param configInfos
     * @return
     */
    private List<NonGridRobOrderConfigDRO> toDRO(List<NonGridRobOrderConfig> configInfos) {
        List<NonGridRobOrderConfigDRO> configDROS = new ArrayList<>(configInfos.size());
        configInfos.stream().forEach(item -> {
            NonGridRobOrderConfigDRO dro = new NonGridRobOrderConfigDRO();
            BeanMapper.copy(item, dro);
            String engineerSource = item.getEngineerCompanyType();
            if (StringUtils.isNotEmpty(engineerSource)) {
                String[] split = engineerSource.split(",");
                for (int i = 0; i < split.length; i++) {
                    if (Objects.equals(split[i], "1")) {
                        dro.setEngineerCompanyTypeOfSubsidiary(Boolean.TRUE);
                    } else if (Objects.equals(split[i], "2")) {
                        dro.setEngineerCompanyTypeOfHomeRepairman(Boolean.TRUE);
                    }
                }
            }
            configDROS.add(dro);
        });
        return configDROS;
    }

    /**
     * db -> VO
     * @param configInfo
     * @return
     */
    private NonGridRobOrderConfigVO toVO(NonGridRobOrderConfig configInfo) {
        NonGridRobOrderConfigVO configVO = new NonGridRobOrderConfigVO();
        BeanUtils.copyProperties(configInfo, configVO);
        String engineerSource = configInfo.getEngineerCompanyType();
        if (StringUtils.isNotEmpty(engineerSource)) {
            String[] split = engineerSource.split(",");
            for (int i = 0; i < split.length; i++) {
                if (Objects.equals(split[i], "1")) {
                    configVO.setEngineerCompanyTypeOfSubsidiary(1);
                } else if (Objects.equals(split[i], "2")) {
                    configVO.setEngineerCompanyTypeOfHomeRepairman(2);
                }
            }
        }
        return configVO;
    }
}
